/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package dawfiltros;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.interfaces.*;
import javax.crypto.spec.*;
//import com.pm.logs.*;
import sun.misc.BASE64Encoder;

/**
 *
 * @author MAR
 */

public class DESEncryptor {

	/**
	 * Encripta los datos pasados por par?metro.
	 *
	 * Genera una clave a partir de la cadena proporcionada, usando MD5.
	 * Realiza la encriptaci?n usando el algoritmo DES.
	 */
	public static byte [] encrypt (String passphrase, byte [] data) throws Exception
	{
		byte [] dataTemp;
		//PMLogger logger = new PMLogger(PMLoggerConstants.DEFECTO);

		try
		{
			Security.addProvider( new com.sun.crypto.provider.SunJCE() );
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(passphrase.getBytes());
			DESKeySpec key = new DESKeySpec (md.digest());
			SecretKeySpec DESKey = new SecretKeySpec (key.getKey(), "DES");
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, DESKey);

			dataTemp = cipher.doFinal (data);

		} catch (Exception e) {
			//logger.error("[com.pm.util.directorio.DESEncryptor][encrypt] Se produjo una excepci?n durante la encriptaci?n: "+e);
			throw e;
		}

		return dataTemp;
	}


	/**
	 * Desencripta los datos pasados por par?metro.
	 *
	 * Genera una clave a partir de la cadena proporcionada, usando MD5.
	 * Realiza la desencriptaci?n usando el algoritmo DES.
	 */
	public static byte [] decrypt (String passphrase, byte [] data) throws Exception
	{
		byte [] dataTemp;
		//PMLogger logger = new PMLogger(PMLoggerConstants.DEFECTO);

		try
		{
			Security.addProvider( new com.sun.crypto.provider.SunJCE() );
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(passphrase.getBytes());
			DESKeySpec key = new DESKeySpec (md.digest());
			SecretKeySpec DESKey = new SecretKeySpec (key.getKey(), "DES");
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.DECRYPT_MODE, DESKey);

			dataTemp = cipher.doFinal (data);

		} catch (Exception e) {
			//logger.error("[com.pm.util.directorio.DESEncryptor][decrypt] Se produjo una excepci?n durante la desencriptaci?n: "+e);
			throw e;
		}

		return dataTemp;
	}


	/**
	 * Ejemplo de utilizaci?n
	 */

	/*public static void main(String[] args) throws Exception
  	{
		
		String sClave = "mama";
		String sDatos ="papa";
		byte [] ba = sDatos.getBytes ();
		System.out.println("CLAVE: " + sClave);
		System.out.println("MENSAJE ORIGINAL: " + new String (ba));

		// Encriptaci?n
      	ba = DESEncryptor.encrypt (sClave, ba);
      	System.out.println("MENSAJE ENCRIPTADO: " + new BASE64Encoder().encodeBuffer (ba));

		// Desencriptaci?n
		ba = DESEncryptor.decrypt (sClave, ba);
      	System.out.println("MENSAJE DESENCRIPTADO: " + new String (ba));
  	}*/

}

